var request= require('request');
var mssql = require('mssql');


var stations = {
	"02004720001000": {
		"mn": "02004720001000",
		"code": "QDDG-2-01-C",
		"stName": "八码头10股3铁路线2"
	},
	"06006360001000": {
		"mn": "06006360001000",
		"code": "QQCT-2-02",
		"stName": "三期L08"
	},
	"02004620001000": {
		"mn": "02004620001000",
		"code": "QDQG-2-02-C",
		"stName": "大护坡办公楼1"
	},
	"01006120001000": {
		"mn": "01006120001000",
		"code": "QDQG-1-01",
		"stName": "职工之家楼顶"
	},
	"06005190001000": {
		"mn": "06005190001000",
		"code": "QQCT-2-01",
		"stName": "QQCT二期10号变电所"
	},
	"06005290001000": {
		"mn": "06005290001000",
		"code": "QDCR-2-01",
		"stName": "长荣三期厂站"
	},
	"06006030001000": {
		"mn": "06006030001000",
		"code": "QDCR-2-02",
		"stName": "长荣四期厂站"
	},
	"01005790001000": {
		"mn": "01005790001000",
		"code": "QQCT-1-01",
		"stName": "81区粉尘"
	},
	"02004660001000": {
		"mn": "02004660001000",
		"code": "QDDG-2-01-A",
		"stName": "八码头10股3铁路线3"
	},
	"06004940001000": {
		"mn": "06004940001000",
		"code": "QQCTU-2-01",
		"stName": "C06监测点"
	},
	"02004730001000": {
		"mn": "02004730001000",
		"code": "QDQG-2-02-A",
		"stName": "大护坡办公楼2"
	},
	"01005970001000": {
		"mn": "01005970001000",
		"code": "QDQG-1-02",
		"stName": "二号磅粉尘"
	},
	"02004600001000": {
		"mn": "02004600001000",
		"code": "QDQG-2-02-B",
		"stName": "大护坡办公楼3"
	},
	"01005190001000": {
		"mn": "01005190001000",
		"code": "",
		"stName": "2019"
	},
	"01005140001000": {
		"mn": "01005140001000",
		"code": "QQCTU-1-01",
		"stName": "A04与S03场区边界"
	},
	"06005720001000": {
		"mn": "06005720001000",
		"code": "QDQG-2-01",
		"stName": "二十万桥世纪之光雕塑"
	},
	"06005890001000": {
		"mn": "06005890001000",
		"code": "QQCTU-2-02",
		"stName": "技术部楼顶"
	},
	"06005960001000": {
		"mn": "06005960001000",
		"code": "QDQG-2-03",
		"stName": "小港池701号堆场"
	},
	"02004770001000": {
		"mn": "02004770001000",
		"code": "QDDG-2-01-B",
		"stName": "八码头10股3铁路线1"
	},
	"01005540001000": {
		"mn": "01005540001000",
		"code": "QDDG-1-01",
		"stName": "7号码头限制区域门岗"
	},
	"06005660001000": {
		"mn": "06005660001000",
		"code": "QQTU-2-01",
		"stName": "职工之家楼顶"
	}
};

class TInf{
    constructor(){
        this.config ={
            api:{
                apiUrl:"http://10.205.21.23:8215",
                uid:"tiankeyuan",
                pwd:"tiankeyuan"
            },
            db:{
                dbName:"mydb",
                url:"http://127.0.0.1:8086",
                logTable:"T_Logs"
            },
            realFields:[
                "co" ,"so2" ,"no2" ,"o3","pm10" ,"pm25" ,"tsp" ,"temp" ,"humidity" ,"windDirection" ,"windSpeed" 
            ],
            stations:{
                
            }
        }
        this.cookieResult="";
        this.session= "";
        this.stations = stations;
    }
    static getHttpResult( url , method, headers , ps , bodyString){
        return new Promise( (success , faild )=>{
            var res ={
                state :0 ,
                data: null ,
                cookieResult :""
            };
            try{
                var urlAdd = url +  (url.indexOf("?")>0?"&":"?");
                urlAdd += "rtm="+Math.random();
                var cookieJar = request.jar();
                var opts ={
                    url:urlAdd ,
                    method: method ,
                    jar : cookieJar
                };
                if( headers && headers!=null){
                    opts.headers = headers;
                }
                if( ps && ps!=null){
                    if( method =="GET"){
                        var psDatas =[];
                        Object.keys(ps).forEach(p=>{
                            psDatas.push( p+"="+ps[p]);
                        })
                        opts.url +="&";
                        opts.url += psDatas.join("&");
                    }
                    else if(method=="POST"){
                        opts.formData  = ps;
                    }
                } 
                if( method == "POST" && bodyString && bodyString!=null){
                    opts.body = bodyString;
                }
                request( opts , function(error, response, body){
                    try{
                        if( body!=''  && body!=null){ 
                            res.state = 1;
                            res.data = JSON.parse(body);
                            res.cookieResult = cookieJar.getCookieString(urlAdd); 
                            me.cookieResult = cookieJar.getCookieString(urlAdd); 
                        }
                    }
                    catch(eer){
                        console.log(eer);
                    }
                    success(res);
                });
            }
            catch(er){
                console.log(er);
            }
        })
    }

    init( ){
        var me = this;
        return new Promise( (success , faild )=>{ 
            try{
                var url = me.config.api.apiUrl+"/login";
                var ps={
                    username:me.config.api.uid,
                    password :me.config.api.pwd,
                    rememberMe: 'false' ,
                    captchaFlag: 'false'
                };
                TInf.getHttpResult(url , "POST" , null , ps , "").then(res=>{
                    me.session = res.state ==1 ? res.cookieResult:"";
                    success();
                })
            }
            catch(er){
                console.log(er);
            }
        })
    } 
    getDataItem ( row ){
        var me = this;
        var res ={};
        try{
            var st = me.stations[row.mn];
            if( st ){
                res.code = st.code ;
                res.time =  ((new Date(row.monitorTime)).getTime()+8*3600*1000)*1000000; 
                res.values = [];
                me.config.realFields.forEach( f=>{
                    var val = row[f];
                    if( val!=null && val>=0){
                        val = val*1.0;
                        res.values.push({
                            dk: f,
                            rtd : val
                        })
                    } 
                })
            }
        }
        catch(er){
            console.log(er)
        }
        return res;
    }
    getRealDatas(){
        var me = this;
        var res = [];
        return new Promise((success , faild)=>{
            try{
                var url = me.config.api.apiUrl +"/feature/datareal/dust/list",
                var headers ={
                    cookie:me.cookieResult
                };
                var ps = null;
                var bodyString= null;
                TInf.getHttpResult( url , "POST" ,  headers , bodyString).then(data=>{
                    try{
                        if( data && data.rows && data.rows.length>0){
                            data.rows.forEach( r=>{
                                var row = me.getDataItem(r);
                                if( row && row.time && row.time>0){
                                    res.push(row);
                                }
                            })
                        }
                    }
                    catch(eer){
                        console.log(eer);
                    }
                })
            }
            catch(er){
                console.log(er);
                success(res);
            }
        })
    }
    getHisDatas( startDt , endDt){
        var me = this;
        var res = [];
        return new Promise((success , faild)=>{
            try{
                var url = me.config.api.apiUrl +"/feature/datareal/dust/list",
                var headers ={
                    cookie:me.cookieResult
                };
                var ps = {
                    "params[beginTime]": startDt ,
                    "params[endTime]": endDt  
                };
                var bodyString= null;
                TInf.getHttpResult( url , "POST" ,  headers , bodyString).then(data=>{
                    try{
                        if( data && data.rows && data.rows.length>0){
                            data.rows.forEach( r=>{
                                var row = me.getDataItem(r);
                                if( row && row.time && row.time>0){
                                    res.push(row);
                                }
                            })
                        }
                    }
                    catch(eer){
                        console.log(eer);
                    }
                })
            }
            catch(er){
                console.log(er);
                success(res);
            }
        })
    }
    toDB( dataItems ){
        var me = this; 
        return new Promise((success , faild)=>{
            try{ 
                if( dataItems && dataItems.length>0){
                    var items =[];
                    dataItems.forEach( di=>{
                        if( di.values && di.values.length>0){
                            var dataStr = me.config.db.logTable + ",";
                            di.values.forEach(v=>{
                                var tags =[
                                    "dk="+ v.dk ,
                                    "code="+ di.code
                                ]
                                var rtdValue = "rtd="+v.rtd;
                                dataStr += tags.join(",") + " "+ rtdValue +" "+di.time;
                                items.push(dataStr);
                            })
                        }
                    })
                    var write2DB = function(){
                        if( items.length>0){
                            var item = items.shift();
                            var url = me.config.db.url+"/write?db="+me.config.db.dbName;
                            TInf.getHttpResult(url , "POST" , null , null , item).then(callRes=>{
                                console.log(item);
                                write2DB();
                            })
                        }
                        else{
                            success();
                        }
                    }
                    write2DB();
                }
            }
            catch(er){
                console.log(er);
                success(res);
            }
        })
    }
    

    getCompanies(   ){
        var me = this;
        return new Promise( (success , faild )=>{ 
            try{
                var url = me.config.api.apiUrl+"/feature/enterprise/list";
                var headers = {
                    Cookie:me.session
                };
                TInf.getHttpResult(url , "POST" , headers , null , null).then(res=>{
                    console.log(res)
                })
            }
            catch(er){
                console.log(er);
            }
        })
    }
    inf2DbData( infData  ){
        var me = this;
        return new Promise((success , faild)=>{
            var res =[];
            try{            
                var mn = infData.mn;
                if( stations[mn] && stations[mn].code.length>0 ){
                    var code = stations[mn].code;
                    var label = infData.monitorPointName;
                    var factory = infData.enterpriseName;
                    var t = ((new Date(infData.monitorTime)).getTime()+8*3600*1000)*1000000; 
                    me.config.realFields.forEach( f=>{
                        var val = infData[f];
                        if( val!=null && val>=0){
                            var tagDict ={
                                "code":code,
                                "dk":f,
                                "enId":"-",
                                "factory":factory,
                                "ip":"0.0.0.0",
                                "label": label, 
                                "type":infData.type
                            };
                            var tags =[];
                            Object.keys(tagDict).forEach( tag=>{
                                tags.push( tag+"="+ tagDict[tag]);
                            })
                            var r = "T_Real,"+ tags.join(",")+ " rtd="+ val+" "+ t.toString();
                            res.push(r);
    
                        }
                    })
    
                }
            }
            catch(er){
                console.log(er);
            }

            var write2DB = function(){
                if( res.length>0){
                    var r = res.shift();
                    var url = me.config.db.url+"/write?db="+me.config.db.dbName;
                    TInf.getHttpResult(url , "POST" , null , null , r).then(callRes=>{
                        console.log(r);
                        write2DB();
                    })
                }
                else{
                    success();
                }
            }
            write2DB();
        }) 
    }
    importReal(   ){
        var me = this;
        return new Promise( (success , faild )=>{ 
            try{
                var url = me.config.api.apiUrl+"/feature/datareal/dust/list";
                var headers = {
                    Cookie:me.session
                };
                var datas =[];
                TInf.getHttpResult(url , "POST" , headers , null , null).then(res=>{
                    console.log(res);
                    var inputItem = function(){
                        if( res.data && res.data.rows && res.data.rows.length>0){
                            var r = res.data.rows.shift();
                            me.inf2DbData(r).then(_=>{
                                inputItem();
                            });    
                        }
                        else{
                            success();
                        }
                    }
                    inputItem();
                })
            }
            catch(er){
                console.log(er);
            }
        })
    }
    importRealLoog(){
        var me = this;
        var acImport= function(){
            me.importReal().then(_=>{
                console.log('-------------------------- import reals ('+( new Date()).toString()+') -------------------------------------')
                setTimeout( acImport , 5*60*1000);
            })
        }
        acImport();
    }
    
}


var a = new TInf();
a.init().then(_=>{
    console.log(a.session );
    return a.importRealLoog();
    console.log('start import real datas.')
});